package com.xdf.vpndialer.service;


import javafx.application.Application;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

@Service
@Slf4j
public class ExecExtFile {

    /**
     * 获取项目加载类的根路径
     * @return
     */
    public String getPath(){
        String path = "";
        try{
            //jar 中没有目录的概念
            URL location = Application.class.getProtectionDomain().getCodeSource().getLocation();//获得当前的URL
            File file = new File(location.getPath());//构建指向当前URL的文件描述符
            if(file.isDirectory()){//如果是目录,指向的是包所在路径，而不是文件所在路径
                path = file.getAbsolutePath();//直接返回绝对路径
            }else{//如果是文件,这个文件指定的是jar所在的路径(注意如果是作为依赖包，这个路径是jvm启动加载的jar文件名)
                path = file.getParent();//返回jar所在的父路径
            }
//            log.info("project path={}",path);
            System.out.println("project path=" + path);
        }catch (Exception e){
            e.printStackTrace();
//            log.error("{}",e);
            System.out.println(e);
        }
        return path;
    }


    public static void main(String args[]){
//        String path = getPath();
//        System.out.println(path);
//        String path = "c:\\vpndialer.bat";
        //callCmd("c:\\windows\\vpndialer\\vpndialer.bat");
    }

    public void callCmd(String locationCmd){
        try {
            Process child = Runtime.getRuntime().exec(locationCmd);
            InputStream in = child.getInputStream();
            int c;
            while ((c = in.read()) != -1) {
                System.out.println((char)c);
            }
            in.close();
            try {
                child.waitFor();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("done");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
